//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.configuration.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.event.MqttMessageDeliveredEvent;
import org.springframework.integration.mqtt.event.MqttMessageSentEvent;
import org.springframework.integration.mqtt.outbound.AbstractMqttMessageHandler;
import org.springframework.integration.mqtt.support.MqttMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.util.Assert;

public class LocalMessageHandler extends AbstractMqttMessageHandler implements MqttCallback, ApplicationEventPublisherAware {
    private static final Logger logger = LoggerFactory.getLogger(LocalMessageHandler.class);
    public static final long DEFAULT_COMPLETION_TIMEOUT = 30000L;
    private long completionTimeout;
    private final MqttPahoClientFactory clientFactory;
    private boolean async;
    private boolean asyncEvents;
    private ApplicationEventPublisher applicationEventPublisher;
    private volatile IMqttAsyncClient client;

    public LocalMessageHandler(String url, String clientId, MqttPahoClientFactory clientFactory) {
        super(url, clientId);
        this.completionTimeout = 30000L;
        this.clientFactory = clientFactory;
    }

    public LocalMessageHandler(String clientId, MqttPahoClientFactory clientFactory) {
        super((String)null, clientId);
        this.completionTimeout = 30000L;
        this.clientFactory = clientFactory;
    }

    public LocalMessageHandler(String url, String clientId) {
        this(url, clientId, new DefaultMqttPahoClientFactory());
    }

    public void setAsync(boolean async) {
        this.async = async;
    }

    public void setAsyncEvents(boolean asyncEvents) {
        this.asyncEvents = asyncEvents;
    }

    public void setCompletionTimeout(long completionTimeout) {
        this.completionTimeout = completionTimeout;
    }

    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    protected void onInit() {
        super.onInit();
        Assert.state(this.getConverter() instanceof MqttMessageConverter, "MessageConverter must be an MqttMessageConverter");
    }

    protected void doStart() {
    }

    protected void doStop() {
        try {
            IMqttAsyncClient theClient = this.client;
            if (theClient != null) {
                theClient.disconnect().waitForCompletion(this.completionTimeout);
                theClient.close();
                this.client = null;
            }
        } catch (MqttException var2) {
            logger.error("Failed to disconnect", var2);
        }

    }

    private synchronized IMqttAsyncClient checkConnection() throws MqttException {
        if (this.client != null && !this.client.isConnected()) {
            this.client.setCallback((MqttCallback)null);
            this.client.close();
            this.client = null;
        }

        if (this.client == null) {
            try {
                MqttConnectOptions connectionOptions = this.clientFactory.getConnectionOptions();
                Assert.state(this.getUrl() != null || connectionOptions.getServerURIs() != null, "If no 'url' provided, connectionOptions.getServerURIs() must not be null");
                this.client = this.clientFactory.getAsyncClientInstance(this.getUrl(), this.getClientId());
                this.incrementClientInstance();
                this.client.setCallback(this);
                this.client.connect(connectionOptions).waitForCompletion(this.completionTimeout);
                if (logger.isDebugEnabled()) {
                    logger.debug("Client connected");
                }
            } catch (MqttException var2) {
                if (this.client != null) {
                    this.client.close();
                    this.client = null;
                }

                throw new MessagingException("Failed to connect", var2);
            }
        }

        return this.client;
    }

    protected void publish(String topic, Object mqttMessage, Message<?> message) throws Exception {
        Assert.isInstanceOf(MqttMessage.class, mqttMessage);
        IMqttDeliveryToken token = this.checkConnection().publish(topic, (MqttMessage)mqttMessage);
        token.isComplete();
        if (!this.async) {
            token.waitForCompletion(this.completionTimeout);
        } else if (this.asyncEvents && this.applicationEventPublisher != null) {
            logger.info(String.format("Publish Message topic [ %s ] localMessageId [ %s ] messageId [ %s ] message [ %s ] clientId [ %s ]", topic, token.getMessageId(), message.getHeaders().get("id"), message.getPayload().toString(), this.getClientId()));
            this.applicationEventPublisher.publishEvent(new MqttMessageSentEvent(this, message, topic, token.getMessageId(), this.getClientId(), this.getClientInstance()));
        }

    }

    private void sendDeliveryComplete(IMqttDeliveryToken token) {
        if (this.async && this.asyncEvents && this.applicationEventPublisher != null) {
            logger.info(String.format("Delivery Complete --- topic [ %s ] messageId [ %s ] clientId [ %s ]", token.getTopics()[0], token.getMessageId(), this.getClientId()));
            this.applicationEventPublisher.publishEvent(new MqttMessageDeliveredEvent(this, token.getMessageId(), this.getClientId(), this.getClientInstance()));
        }

    }

    public synchronized void connectionLost(Throwable cause) {
        logger.error("Lost connection; will attempt reconnect on next request");
        if (this.client != null) {
            try {
                this.client.setCallback((MqttCallback)null);
                this.client.close();
            } catch (MqttException var3) {
            }

            this.client = null;
        }

    }

    public void messageArrived(String topic, MqttMessage message) {
        logger.info(String.format("topic [ %s ] message [ %s ]", topic, new String(message.getPayload())));
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        this.sendDeliveryComplete(token);
    }
}
